/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amse.grigory.dchess.view;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import org.amse.grigory.dchess.io.ConfigLoader;
import org.amse.grigory.dchess.io.GameLoader;
import org.amse.grigory.dchess.player.AIPlayer;
import org.amse.grigory.dchess.player.GameControler;
import org.amse.grigory.dchess.player.IPlayer;
import org.amse.grigory.dchess.player.LocalPlayer;
import org.amse.grigory.dchess.rules.Rules;

/**
 *
 * @author grigory
 */
public class OpenGameDialog extends JDialog {

    private JTextField myTextField;
    private int myState = 0;
    private boolean myExit = false;
    private JComboBox myComboBoxTheme,  myComboBoxWhite,  myComboBoxBlack;
    private ConfigLoader myConfig;

    private OpenGameDialog() {
    }

    public OpenGameDialog(final DChessFrame frame) {
        super(frame, true);
        setSize(300, 350);
        setLocation(frame.getLocation().x + 100, frame.getLocation().y + 100);
        setResizable(false);
        Container c = getContentPane();
        myConfig = frame.getConfig();
        Dimension dim = new Dimension(25, 200);
        createComboBoxes();
        SpinnerModel numbers = new SpinnerNumberModel(300, 10, 300000000, 1);
        myComboBoxTheme.setAlignmentX(LEFT_ALIGNMENT);


        //Panels layouts
        JPanel panelGame = createPanelGame();
        JPanel panelPlayers = createPanelPlayers();
        JPanel panelButtons = createPanelButtons();

        c.setLayout(new FlowLayout());
        panelGame.setPreferredSize(new Dimension(280, 150));
        panelPlayers.setPreferredSize(new Dimension(280, 100));
        panelButtons.setPreferredSize(new Dimension(280, 100));
        //c.setLayout(new GridLayout(3, 1));
        c.add(panelGame);
        c.add(panelPlayers);
        c.add(panelButtons);

        setSize(300, 350);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new DChessListener(frame));
        setVisible(true);

    }

    private JPanel createPanelButtons() {

        // buttons
        JButton buttonOK = new JButton("OK");
        buttonOK.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                myState = 1;
                OpenGameDialog.this.dispose();
            }
        });
        JButton buttonCancel = new JButton("Cancel");
        buttonCancel.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                OpenGameDialog.this.dispose();
            }
        });



        buttonCancel.setAlignmentX(LEFT_ALIGNMENT);
        buttonOK.setAlignmentX(LEFT_ALIGNMENT);
        Dimension dim = new Dimension(75, 25);
        buttonOK.setSize(dim);
        buttonOK.setPreferredSize(dim);
        buttonOK.setMaximumSize(dim);
        buttonOK.setMinimumSize(dim);
        buttonCancel.setSize(dim);
        buttonCancel.setPreferredSize(dim);
        buttonCancel.setMaximumSize(dim);
        buttonCancel.setMinimumSize(dim);

        //panels
        JPanel panelButtons = new JPanel();
        JPanel panelBut = new JPanel();
        panelButtons.setLayout(new GridLayout(2, 1));
        panelBut.setLayout(new BoxLayout(panelBut, BoxLayout.X_AXIS));

        panelButtons.add(panelBut);
        panelBut.add(Box.createHorizontalGlue());
        panelBut.add(buttonOK);
        panelBut.add(Box.createHorizontalGlue());
        panelBut.add(buttonCancel);
        panelBut.add(Box.createHorizontalGlue());

        return panelButtons;
    }

    private JPanel createPanelPlayers() {
        JPanel panelPlayers = new JPanel();
        JPanel panelWhite = new JPanel();
        JPanel panelBLack = new JPanel();
        JLabel l3 = new JLabel("White:");
        JLabel l4 = new JLabel("Black:");

        panelPlayers.setBorder(BorderFactory.createTitledBorder("Players"));
        panelPlayers.setLayout(new GridLayout(2, 1));

        panelBLack.setLayout(new BoxLayout(panelBLack, BoxLayout.X_AXIS));
        panelWhite.setLayout(new BoxLayout(panelWhite, BoxLayout.X_AXIS));

        panelWhite.add(l3);
        panelWhite.add(Box.createHorizontalGlue());
        panelWhite.add(myComboBoxWhite);
        panelBLack.add(l4);
        panelBLack.add(Box.createHorizontalGlue());
        panelBLack.add(myComboBoxBlack);

        panelPlayers.add(panelWhite);
        panelPlayers.add(panelBLack);

        return panelPlayers;
    }

    private JPanel createPanelGame() {
        JPanel panelGame = new JPanel();
        JPanel PTheme = new JPanel();
        JPanel PSaveGame = new JPanel();
        JLabel l2 = new JLabel("Theme:");
        JLabel l3 = new JLabel("Save:");
        JTextField dest= new JTextField();
        

        PTheme.setLayout(new BoxLayout(PTheme, BoxLayout.X_AXIS));
        PSaveGame.setLayout(new BoxLayout(PSaveGame, BoxLayout.X_AXIS));

        panelGame.setBorder(BorderFactory.createTitledBorder("Game"));
        panelGame.setLayout(new GridLayout(3, 1));

        panelGame.add(PTheme);
        panelGame.add(PSaveGame);
        
        PTheme.add(l2);
        PSaveGame.add(l3);
        PSaveGame.add(Box.createHorizontalGlue());
        PSaveGame.add(dest);
        PSaveGame.add(new JButton(new OpenAction()));
        Dimension dim=new Dimension(157, 25);
        dest.setPreferredSize(dim);
        dest.setMaximumSize(dim);
        dest.setMinimumSize(dim);
        myTextField=dest;        

        PTheme.add(Box.createHorizontalGlue());
        PTheme.add(myComboBoxTheme);

        return panelGame;
    }

    private class OpenAction extends AbstractAction {

        public OpenAction() {
            putValue(NAME, "...");
            putValue(SHORT_DESCRIPTION, "Open saved game");
        }

        public void actionPerformed(ActionEvent e) {            
            JFileChooser fc = new JFileChooser();
            fc.setDialogTitle("Open Game");
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fc.setFileFilter(Filters.getGameFilter());
            fc.setCurrentDirectory(new File("."));
            int res =  fc.showOpenDialog(OpenGameDialog.this);
            if ((res == JFileChooser.APPROVE_OPTION)) {
                try {
                    File f=fc.getSelectedFile();
                    if (!f.getName().endsWith("xml")){
                        f=new File(f.getName()+".xml");
                    }
                    myTextField.setText(f.getPath());
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(rootPane, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        
    }

    private void createComboBoxes() {
        String[] rname, tname;
        // first combobox
        rname = new String[myConfig.getRulesCount()];
        for (int i = 0; i < myConfig.getRulesCount(); i++) {
            rname[i] = myConfig.getRulesName(i);
        }
        Dimension dim = new Dimension(200, 25);

        // second combobox
        tname = new String[myConfig.getThemeCount()];
        for (int i = 0; i < myConfig.getThemeCount(); i++) {
            tname[i] = myConfig.getThemeName(i);
        }
        myComboBoxTheme = new JComboBox(tname);
        myComboBoxTheme.setPreferredSize(dim);
        myComboBoxTheme.setMaximumSize(dim);


        String players[] = {"Local", "AI"};

        //two more combox
        myComboBoxWhite = new JComboBox(players);
        myComboBoxWhite.setPreferredSize(dim);
        myComboBoxWhite.setMaximumSize(dim);
        myComboBoxBlack = new JComboBox(players);
        myComboBoxBlack.setPreferredSize(dim);
        myComboBoxBlack.setMaximumSize(dim);
    }

    private class DChessListener extends WindowAdapter {

        private DChessFrame myFrame;

        public DChessListener(DChessFrame frame) {
            myFrame = frame;
        }

        @Override
        public void windowClosing(WindowEvent e) {
            OpenGameDialog.this.dispose();
        }

        @Override
        public void windowClosed(WindowEvent e) {
            if (!myExit) {
                myFrame.setFocusableWindowState(true);
                myFrame.setEnabled(true);
                if (myState == 1) {
                    int j = myComboBoxTheme.getSelectedIndex();
                    myFrame.setTheme(myConfig.getTheme(j));
                    IPlayer pw = null;
                    String sw = (String) myComboBoxWhite.getSelectedItem();
                    if (sw.equals("Local")) {
                        pw = new LocalPlayer();
                    }
                    if (sw.equals("AI")) {
                        pw = new AIPlayer(3, myFrame.getModel());
                        pw.setColor(Rules.COLOR_WHITE);
                    }
                    IPlayer pb = null;
                    String sb = (String) myComboBoxBlack.getSelectedItem();
                    if (sb.equals("Local")) {
                        pb = new LocalPlayer();
                    }
                    if (sb.equals("AI")) {
                        pb = new AIPlayer(3, myFrame.getModel());
                        pb.setColor(Rules.COLOR_BLACK);
                    }
                    GameControler gamec = new GameControler(myFrame.getModel(), pw, pb);
                    myFrame.openGame(gamec,myTextField.getText());
                    myExit = true;
                }
            }
        }
    }
}
